package org.ssi.web.result;
/*
 * XMLNodeResult.java
 *
 * Copyright 2009 Handlewell Beijing Inc.
 * All rights reserved.
 * 
 * Created on 2009-12-17
 */
import java.io.OutputStream;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * 功能概述：<br>
 * 针对com.handlewell.adp.support.XMLNodeWriter序列化输出
 * 
 * @author 王国东
 */
public class XMLNodeResult implements Result {
	/**   */
	private static final long serialVersionUID = 1L;

	private static final Log log = LogFactory.getLog(XMLNodeResult.class);

	/** 序列化结点名称 */
	private String nodeName = "xmlNode";

	/** 字符编码 */
	private String encoding = "UTF-8";

	/**
	 * 
	 * @see com.opensymphony.xwork2.Result#execute(com.opensymphony.xwork2.ActionInvocation)
	 */
	public void execute(ActionInvocation invocation) throws Exception {
		/* 取得XMLNode结点的值 */
		ActionContext invokeContext = invocation.getInvocationContext();
		ValueStack stack = invokeContext.getValueStack();
		Object retValue = stack.findValue(this.nodeName);
		if (retValue == null) {
			log.error("The Property Value Of \"" + nodeName
					+ "\" Must be Not Null");
			return;
		}

		/* 将序列后的XML结点内容输出回复流当中 */
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/xml;charset=" + this.encoding);
		OutputStream out = response.getOutputStream();
		XMLNodeWriter writer = new XMLNodeWriter((XMLNode) retValue);
		Charset charset = Charset.forName(this.encoding);
		writer.writeXmlContent(charset, out);
		out.flush();
	}

	/**
	 * @return Returns the nodeName.
	 */
	public String getNodeName() {
		return nodeName;
	}

	/**
	 * @param nodeName
	 *            The nodeName to set.
	 */
	public void setNodeName(String nodeName) {
		this.nodeName = nodeName;
	}

	/**
	 * @return Returns the encoding.
	 */
	public String getEncoding() {
		return encoding;
	}

	/**
	 * @param encoding
	 *            The encoding to set.
	 */
	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

}
